/*
 * Copyright 2010 Electronic Business Systems Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package gr.ebs.gssdroid.activities;

import gr.ebs.gssdroid.GssDroid;
import gr.ebs.gssdroid.R;
import gr.ebs.gssdroid.async.GssAsyncTask;
import gr.ebs.gssdroid.async.TaskResult;
import gr.ebs.gssdroid.http.GssHttpCommands;
import gr.ebs.gssdroid.resource.BackResource;
import gr.ebs.gssdroid.resource.FileResource;
import gr.ebs.gssdroid.resource.FolderResource;
import gr.ebs.gssdroid.resource.RestResource;
import gr.ebs.gssdroid.resource.SharedResource;
import gr.ebs.gssdroid.widget.CustomListAdapter;
import gr.ebs.gssdroid.widget.CustomListView;
import gr.ebs.gssdroid.widget.SharedListAdapter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.TextView;

public class GssShared extends GssMyFolders{
	SharedResource sharedResource;
	RestResource currentResource;
	SharedListAdapter adapter;
	@Override
	protected void initialize() {
		adapter = new SharedListAdapter((Activity) this, R.layout.row,
				new ArrayList<RestResource>()){
			public void onItemClick(final int position, final View v) {
				RestResource entry = getAdapter().getItem(position);
				RestResource toUse = entry;

				Intent intent = new Intent(getApplication(), GssProperties.class);
				intent.putExtra("resource", toUse);
				startActivityForResult(intent, 2009);

			};
		};
		((CustomListView) findViewById(R.id.fileListView)).setAdapter(adapter);
		if(getDroidApplication().getUserResource()==null||getDroidApplication().getUserResource().getFilesPath()==null){
			handleLogin();
			finish();
			return;
		}
		getSharedTask().execute(getDroidApplication().getUserResource().getSharedPath());
	}
	
	
	
	protected void onEntrySelected(int position, final RestResource resource) {
		if (resource instanceof BackResource) {
			if(((BackResource)resource).getResourceClass().equals(SharedResource.class))
				getSharedTask().execute(resource.getUri());
			else
				getTasks().getFolderTask(this).execute(resource.getUri());
		}
		else if (resource instanceof FolderResource) {
			currentResource=(FolderResource) resource;
			String pathToGet= resource.getUri();
			getTasks().getFolderTask(this).execute(pathToGet);
		} else if (resource instanceof FileResource) {
			long filesize = ((FileResource)resource).getContentLength();
			if(filesize>5000000L){
				AlertDialog alertDialogn = new AlertDialog.Builder(this).create();
				alertDialogn.setTitle("Large file size");
				alertDialogn.setMessage("File size is too large are you sure you want to proceed with download?");
				alertDialogn.setButton("Continue",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								getTasks().getFileTask(GssShared.this).execute(((FileResource)resource).getUri());
								dialog.dismiss();
							}
						});
				alertDialogn.setButton2("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						});
				alertDialogn.setCancelable(true);
				alertDialogn.show();
			}
			else{
				getTasks().getFileTask(this).execute(((FileResource)resource).getUri());
			}

		}

	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		onEntrySelected(arg2, adapter.getItem(arg2));
	}

	protected void populateList(RestResource resource) {
		if (resource instanceof SharedResource) {
			sharedResource = (SharedResource) resource;
			List<FolderResource> folders = ((SharedResource) resource).getFolders();
			Iterator<FolderResource> it = folders.iterator();
			while (it.hasNext()) {
				if (!it.next().getUri()
						.startsWith(GssDroid.BASE_REST_URL + getDroidApplication().getUserDetails().getUsername())) {
					it.remove();
				}
			}
			ArrayList<RestResource> data = new ArrayList<RestResource>();
			currentResource=resource;
			data.addAll(((SharedResource)resource).getFolders());
			for(FileResource r : ((SharedResource) resource).getFiles())
				if(!r.isDeleted())
					data.add(r);
			//data.addAll(((SharedResource)resource).getFiles());
			adapter.setListItems(data);
			adapter.notifyDataSetChanged();
			((TextView) findViewById(R.id.textPath)).setText("My Shared files");
			ImageButton newButton = (ImageButton) findViewById(R.id.newBottomItem);
			newButton.setVisibility(View.INVISIBLE);
		} 
		else if(resource instanceof FolderResource){
			boolean isFirstChild = isFolderFirstChildOfShared((FolderResource) resource);
			ArrayList<RestResource> data = new ArrayList<RestResource>();
			if(isFirstChild)
				data.add(new BackResource(sharedResource.getUri(), "My Shared Files", SharedResource.class, currentResource));
			else
				data.add(new BackResource(((FolderResource)resource).getParentURI(), ((FolderResource)resource).getParentName(), FolderResource.class, currentResource));
			//adapter.setRootMode(false);
			currentResource=resource;
			
			data.addAll(((FolderResource)resource).getFolders());
			for(FileResource r : ((FolderResource) resource).getFiles())
				if(!r.isDeleted())
					data.add(r);
			//data.addAll(((FolderResource)resource).getFiles());
			adapter.setListItems(data);
			adapter.notifyDataSetChanged();
			((TextView) findViewById(R.id.textPath)).setText(((FolderResource)resource).getName()+" files");
			ImageButton newButton = (ImageButton) findViewById(R.id.newBottomItem);
			newButton.setVisibility(View.VISIBLE);
		}
		
	}
	

	
	private boolean isFolderFirstChildOfShared(FolderResource folder) {
		for (FolderResource r : sharedResource.getFolders()) {
			String uri = r.getUri();
			if (folder.getUri().equals(uri))
				return true;
		}
		return sharedResource.getFolders().contains(folder);
	}

	private GssAsyncTask getSharedTask() {
		GssAsyncTask getTrashTask = new GssAsyncTask(getDroidApplication().getUserDetails()) {
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				myprogress = ProgressDialog.show(GssShared.this,
						"Fetching Data", "Please Wait", true, false);
				// if(myprogress==null || !myprogress.isShowing()){

				// }
			}

			@Override
			protected RestResource doExecution(String[] params)
					throws Exception {
				return new GssHttpCommands(getDroidApplication().getUserDetails())
						.getSharedResource(params[0]);
			}

			@Override
			protected void onPostExecute(TaskResult result) {
				myprogress.hide();
				if (result.getResource() != null)
					populateList((SharedResource) result.getResource());
				else if (result.getException() != null)
					handleRestException("TRASH", result.getException());
				super.onPostExecute(result);
			}
		};
		return getTrashTask;
	}
	
	protected CustomListAdapter<RestResource> getAdapter(){
		return adapter;
	}
	
	protected void refresh(){
		if(currentResource instanceof FolderResource)
			getTasks().getFolderTask(this).execute(currentResource.getUri());
		else
			getSharedTask().execute(getDroidApplication().getUserResource().getSharedPath());
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (getAdapter().getCount() > 0 && getAdapter().getItem(0) instanceof BackResource) {
			BackResource back = (BackResource) getAdapter().getItem(0);
			if(back.getResourceClass()==FolderResource.class)
				getTasks().getFolderTask(GssShared.this).execute(back.getUri());
			else
				getTasks().getSharedTask(GssShared.this).execute(back.getUri());
		} else {
			super.onBackPressed();
		}
	}
	
	@Override
	public RestResource getCurrentResource() {
		return currentResource;
	}
}
